<template>
  <div class="config-container">
    <el-card class="config-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">外部系统Token配置</span>
          <div class="card-actions">
            <el-button type="primary" @click="testTokens" :loading="testing">
              测试连接
            </el-button>
            <el-button type="success" @click="saveConfig" :loading="saving">
              保存配置
            </el-button>
          </div>
        </div>
      </template>

             <el-form
         ref="configFormRef"
         :model="configForm"
         :rules="configRules"
         label-width="180px"
         class="config-form"
       >
        <el-form-item label="晓风订单Token" prop="xiaofeng_order_token">
          <el-input
            v-model="configForm.xiaofeng_order_token"
            type="password"
            placeholder="请输入晓风订单系统的访问Token"
            show-password
            clearable
          >
            <template #prepend>
              <el-icon><Key /></el-icon>
            </template>
          </el-input>
          <div class="form-tip">
            <el-icon><InfoFilled /></el-icon>
            <span>用于访问晓风订单系统的API接口</span>
          </div>
        </el-form-item>

        <el-form-item label="晓风下单Token" prop="xiaofeng_create_order_token">
          <el-input
            v-model="configForm.xiaofeng_create_order_token"
            type="password"
            placeholder="请输入晓风下单系统的访问Token"
            show-password
            clearable
          >
            <template #prepend>
              <el-icon><Key /></el-icon>
            </template>
          </el-input>
          <div class="form-tip">
            <el-icon><InfoFilled /></el-icon>
            <span>用于访问晓风下单系统的API接口</span>
          </div>
        </el-form-item>
      </el-form>

      <!-- 测试结果 -->
      <div v-if="testResults.length > 0" class="test-results">
        <h4>测试结果</h4>
        <el-alert
          v-for="result in testResults"
          :key="result.key"
          :title="result.name"
          :description="result.message"
          :type="result.status === 'success' ? 'success' : 'error'"
          show-icon
          :closable="false"
          class="test-result-item"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Key, InfoFilled } from '@element-plus/icons-vue'
import { useApi } from '@/composables/useApi'

const api = useApi()

// 表单数据
const configForm = reactive({
  xiaofeng_order_token: '',
  xiaofeng_create_order_token: ''
})

// 表单验证规则
const configRules = {
  xiaofeng_order_token: [
    { required: true, message: '请输入晓风订单Token', trigger: 'blur' }
  ],
  xiaofeng_create_order_token: [
    { required: true, message: '请输入晓风下单Token', trigger: 'blur' }
  ]
}

// 状态
const saving = ref(false)
const testing = ref(false)
const testResults = ref<any[]>([])

// 表单引用
const configFormRef = ref()

// 加载配置
const loadConfig = async () => {
  try {
          const response = await api.get('/system-configs/external-api')
    if (response.code === 200) {
      const data = response.data
      configForm.xiaofeng_order_token = data.xiaofeng_order_token?.value || ''
      configForm.xiaofeng_create_order_token = data.xiaofeng_create_order_token?.value || ''
    }
  } catch (error) {
    console.error('加载配置失败:', error)
    ElMessage.error('加载配置失败')
  }
}

// 保存配置
const saveConfig = async () => {
  try {
    await configFormRef.value?.validate()
    
    saving.value = true
          const response = await api.put('/system-configs/external-api', configForm)
    
    if (response.code === 200) {
      ElMessage.success('配置保存成功')
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error) {
    console.error('保存配置失败:', error)
    ElMessage.error('保存配置失败')
  } finally {
    saving.value = false
  }
}

// 测试Token连接
const testTokens = async () => {
  try {
    testing.value = true
          const response = await api.get('/system-configs/test-token')
    
    if (response.code === 200) {
      const results = response.data
      testResults.value = Object.keys(results).map(key => ({
        key,
        name: key === 'xiaofeng_order_token' ? '晓风订单Token' : '晓风下单Token',
        status: results[key].status,
        message: results[key].message
      }))
      
      const hasError = testResults.value.some(result => result.status === 'error')
      if (hasError) {
        ElMessage.warning('部分Token配置有问题，请检查')
      } else {
        ElMessage.success('所有Token配置正常')
      }
    } else {
      ElMessage.error(response.message || '测试失败')
    }
  } catch (error) {
    console.error('测试Token失败:', error)
    ElMessage.error('测试Token失败')
  } finally {
    testing.value = false
  }
}

// 页面加载时获取配置
onMounted(() => {
  loadConfig()
})
</script>

<style scoped>
.config-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.config-card {
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.card-actions {
  display: flex;
  gap: 10px;
}

.config-form {
  margin-top: 20px;
}

.form-tip {
  display: flex;
  align-items: center;
  gap: 5px;
  margin-top: 5px;
  color: #909399;
  font-size: 12px;
}

.form-tip .el-icon {
  color: #409eff;
}

.test-results {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.test-results h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
}

.test-result-item {
  margin-bottom: 10px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-input-group__prepend) {
  background-color: #f5f7fa;
  border-color: #dcdfe6;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}
</style> 